Creating tables from scratch is a pain.
This is why there are many table plugins to let us add tables easily.
In this article, we’ll look at how to add tables to a Vue app with the vue-good-table plugin.
Changing Options
The vue-good-table plugin provides us with many options for customizing our tables.
One of them is the line number option. This lets us show the line number on each row.
To add this, we add the line-numbers
prop:
<template>
<div>
<vue-good-table :columns="columns" :rows="rows" line-numbers/>
</div>
</template>
<script>
export default {
data() {
return {
columns: [
{
label: "Name",
field: "name"
},
{
label: "Age",
field: "age",
type: "number"
},
{
label: "Birthday",
field: "birthDay",
type: "date",
dateInputFormat: "yyyy-MM-dd",
dateOutputFormat: "MMM do yy"
}
],
rows: [
{ id: 1, name: "John", age: 20, birthDay: "2000-01-20" },
{ id: 2, name: "Jane", age: 24, birthDay: "1996-10-31" },
{ id: 3, name: "Susan", age: 16, birthDay: "2004-10-30" }
]
};
}
};
</script>
The row styles can be customized by adding a row-style-class
prop to add a CSS class to each row.
For example, we can write:
<template>
<div>
<vue-good-table :columns="columns" :rows="rows" :row-style-class="rowStyleClassFn"/>
</div>
</template>
<script>
export default {
data() {
return {
columns: [
{
label: "Name",
field: "name"
},
{
label: "Age",
field: "age",
type: "number"
},
{
label: "Birthday",
field: "birthDay",
type: "date",
dateInputFormat: "yyyy-MM-dd",
dateOutputFormat: "MMM do yy"
}
],
rows: [
{ id: 1, name: "John", age: 20, birthDay: "2000-01-20" },
{ id: 2, name: "Jane", age: 24, birthDay: "2011-10-31" },
{ id: 3, name: "Susan", age: 16, birthDay: "2011-10-30" }
]
};
},
methods: {
rowStyleClassFn(row) {
return row.age > 18 ? "green" : "red";
}
}
};
</script>
<style>
.green {
background-color: green;
}
.red {
background-color: red;
}
td {
color: white !important;
}
</style>
We set the rowStyleClassFn
function as the row-style-class
prop.
Then we can apply the styles we want according to the classes.
The rtl
prop lets us enable the right to left layout for the table.
For example, we can write:
<template>
<div>
<vue-good-table :columns="columns" :rows="rows" rtl/>
</div>
</template>
<script>
export default {
data() {
return {
columns: [
{
label: "Name",
field: "name"
},
{
label: "Age",
field: "age",
type: "number"
},
{
label: "Birthday",
field: "birthDay",
type: "date",
dateInputFormat: "yyyy-MM-dd",
dateOutputFormat: "MMM do yy"
}
],
rows: [
{ id: 1, name: "John", age: 20, birthDay: "2000-01-20" },
{ id: 2, name: "Jane", age: 24, birthDay: "1996-10-31" },
{ id: 3, name: "Susan", age: 16, birthDay: "2004-10-30" }
]
};
}
};
</script>
We flip the columns once we added the rtl
prop.
Conclusion
We can change our tables with various props with vue-good-table.